Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 1: Dataset Exploration

Visualize the German Traffic Signs Dataset. This is open ended, some suggestions include: plotting traffic signs images, plotting the count of each sign, etc. Be creative!

The pickled data is a dictionary with 4 key/value pairs:

  • features -> the images pixel values, (width, height, channels)
  • labels -> the label of the traffic sign
  • sizes -> the original width and height of the image, (width, height)
  • coords -> coordinates of a bounding box around the sign in the image, (x1, y1, x2, y2). Based the original image (not the resized version).
In [1]:
print('Loading data...')
# Load pickled data
import pickle

training_file = './train.p'
testing_file = './test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)

train_features, train_labels = train['features'], train['labels']
test_features, test_labels = test['features'], test['labels']

print('Done loading data')
Loading data...
Done loading data
In [2]:
### To start off let's do a basic data summary.
n_train = len(train_features)
n_test = len(test_features)
image_shape = "{}x{}".format(len(train_features[0]), len(train_features[0][0]))
n_classes = max(train_labels) + 1

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 39209
Number of testing examples = 12630
Image data shape = 32x32
Number of classes = 43
In [3]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage

train_features = np.array(train['features'])
train_labels = np.array(train['labels'])

inputs_per_class = np.bincount(train_labels)
max_inputs = np.max(inputs_per_class)

mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)
ax.set_ylabel('Inputs')
ax.set_xlabel('Class')
ax.set_title('Number of inputs per class')
ax.bar(range(len(inputs_per_class)), inputs_per_class, 1/3, color='blue', label='Inputs per class')
plt.show()

for i in range(n_classes):
    for j in range(len(train_labels)):
        if (i == train_labels[j]):
            print('Class: ', i)
            plt.imshow(train_features[j])
            plt.show()
            break

print('Data visualisation complete')
Class:  0
Class:  1
Class:  2
Class:  3
Class:  4
Class:  5
Class:  6
Class:  7
Class:  8
Class:  9
Class:  10
Class:  11
Class:  12
Class:  13
Class:  14
Class:  15
Class:  16
Class:  17
Class:  18
Class:  19
Class:  20
Class:  21
Class:  22
Class:  23
Class:  24
Class:  25
Class:  26
Class:  27
Class:  28
Class:  29
Class:  30
Class:  31
Class:  32
Class:  33
Class:  34
Class:  35
Class:  36
Class:  37
Class:  38
Class:  39
Class:  40
Class:  41
Class:  42
Data visualisation complete

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Your model can be derived from a deep feedforward net or a deep convolutional network.
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [4]:
print('Preprocessing data...')
# Generate additional data for underrepresented classes
print('Generating additional data...')
angles = [-5, 5, -10, 10, -15, 15, -20, 20]

for i in range(len(inputs_per_class)):
    input_ratio = min(int(max_inputs / inputs_per_class[i]) - 1, len(angles) - 1)

    if input_ratio <= 1:
        continue

    new_features = []
    new_labels = []
    mask = np.where(train_labels == i)

    for j in range(input_ratio):
        for feature in train_features[mask]:
            new_features.append(scipy.ndimage.rotate(feature, angles[j], reshape=False))
            new_labels.append(i)

    train_features = np.append(train_features, new_features, axis=0)
    train_labels = np.append(train_labels, new_labels, axis=0)

# Normalize features
print('Normalizing features...')
train_features = train_features / 255. * 0.8 + 0.1

# Get randomized datasets for training and validation
print('Randomizing datasets...')
from sklearn.model_selection import train_test_split
train_features, valid_features, train_labels, valid_labels = train_test_split(
   train_features,
   train_labels,
   test_size=0.2,
   random_state=832289
)

print('Data preprocessed')
Preprocessing data...
Generating additional data...
Normalizing features...
Randomizing datasets...
Data preprocessed
In [5]:
inputs_per_class = np.bincount(train_labels)
mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)
ax.set_ylabel('Inputs')
ax.set_xlabel('Class')
ax.set_title('Number of inputs per class')
ax.bar(range(len(inputs_per_class)), inputs_per_class, 1/3, color='blue', label='Inputs per class')
plt.show()
In [ ]:
 
In [6]:
print('Creating network architecture...')
import tensorflow as tf
# Input dimensions
image_width = len(train_features[0][0])
image_height = len(train_features[0])
color_channels = len(train_features[0][0][0])

# Convolutional layer patch and output size
filter_width = 3
filter_height = 3
conv_k_output = 128

# Dimension parameters for each fully connected layer
fc_params = [
    image_width * image_height * conv_k_output,
    1024,
    1024,
    n_classes
]

# Build weights and biases
conv2d_weight = None
conv2d_bias = None
fc_weights = []
fc_biases = []

with tf.variable_scope('BONHOMME', reuse=False):
    conv2d_weight = tf.get_variable("conv2w", shape=[filter_width, filter_height, color_channels, conv_k_output], initializer=tf.contrib.layers.xavier_initializer())
    conv2d_bias = tf.get_variable("conv2b", shape=[conv_k_output], initializer=tf.contrib.layers.xavier_initializer())
    
    for i in range(len(fc_params) - 1):
        fc_weights.append(tf.get_variable('fc_weight' + str(i), shape=[fc_params[i], fc_params[i + 1]], initializer=tf.contrib.layers.xavier_initializer()))
        fc_biases.append(tf.get_variable('fc_bias' + str(i), shape=[fc_params[i + 1]], initializer=tf.contrib.layers.xavier_initializer()))

# One-hot encoded training and validation labels
oh_train_labels = tf.one_hot(train_labels, n_classes).eval(session=tf.Session())
oh_valid_labels = tf.one_hot(valid_labels, n_classes).eval(session=tf.Session())

# Input placeholders
input_ph = tf.placeholder(tf.float32, shape=[None, image_width, image_height, color_channels])
labels_ph = tf.placeholder(tf.float32)

# Convolutional layer
network = tf.nn.conv2d(input_ph, conv2d_weight, strides=[1, 1, 1, 1], padding='SAME')
network = tf.nn.bias_add(network, conv2d_bias)
network = tf.nn.relu(network)

# Fully connected layers
for i in range(len(fc_weights)):
    network = tf.matmul(tf.contrib.layers.flatten(network), fc_weights[i]) + fc_biases[i]
    if i < len(fc_weights) - 1: # No relu after last FC layer
        network = tf.nn.relu(network)

# Loss computation
prediction = tf.nn.softmax(network)
cross_entropy = -tf.reduce_sum(labels_ph * tf.log(prediction + 1e-6), reduction_indices=1)
loss = tf.reduce_mean(cross_entropy)

# Accuracy computation
is_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels_ph, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))

print('Network architecture created')
Creating network architecture...
Network architecture created
In [7]:
test_features = np.array(test_features) / 255 * 0.8 + 0.1
oh_test_labels = tf.one_hot(test_labels, n_classes).eval(session=tf.Session())
print('Test label one hot encoded')
Test label one hot encoded
In [8]:
batch_size = 150

def run_batch(session, network, features, labels):
    batch_count = int(len(features) / batch_size)
    accuracy = 0
    
    for i in range(batch_count):
        batch_start = i * batch_size
        accuracy += session.run(
            network,
            feed_dict={
                input_ph: features[batch_start:batch_start + batch_size],
                labels_ph: labels[batch_start:batch_start + batch_size]
            }
        )
    
    return accuracy / batch_count

print('Run batch function created')
Run batch function created
In [9]:
from tqdm import tqdm

training_epochs = 100
optimizer = tf.train.AdamOptimizer().minimize(loss)

log_batch_step = 100
batches = []
loss_batch = []
train_acc_batch = []
valid_acc_batch = []
validation_accuracy = 0.0

init = tf.global_variables_initializer()

session = tf.Session(config=tf.ConfigProto(log_device_placement=True))
session.run(init)
batch_count = int(len(train_features) / batch_size)

for epoch in range(training_epochs):
    batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch + 1, training_epochs), unit='batches')

    # The training cycle
    for batch_i in batches_pbar:
        batch_start = batch_i * batch_size
        batch_features = train_features[batch_start:batch_start + batch_size]
        batch_labels = oh_train_labels[batch_start:batch_start + batch_size]

        _, l = session.run(
            [optimizer, loss],
            feed_dict={input_ph: batch_features, labels_ph: batch_labels})

        if not batch_i % log_batch_step:
            training_accuracy = session.run(
                accuracy,
                feed_dict={input_ph: batch_features, labels_ph: batch_labels}
            )

            idx = np.random.randint(len(valid_features), size=int(batch_size * .2))

            validation_accuracy = session.run(
                accuracy,
                feed_dict={input_ph: valid_features[idx,:], labels_ph: oh_valid_labels[idx,:]}
            )

            # Log batches
            previous_batch = batches[-1] if batches else 0
            batches.append(log_batch_step + previous_batch)
            loss_batch.append(l)
            train_acc_batch.append(training_accuracy)
            valid_acc_batch.append(validation_accuracy)


validation_accuracy = run_batch(session, accuracy, valid_features, oh_valid_labels)    
test_accuracy = run_batch(session, accuracy, test_features, oh_test_labels)

print('Final validation accuracy: ', validation_accuracy)
print('Final test accuracy: ', test_accuracy)
loss_plot = plt.subplot(211)
loss_plot.set_title('Loss')
loss_plot.plot(batches, loss_batch, 'g')
loss_plot.set_xlim([batches[0], batches[-1]])
acc_plot = plt.subplot(212)
acc_plot.set_title('Accuracy')
acc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')
acc_plot.plot(batches, valid_acc_batch, 'b', label='Validation Accuracy')
acc_plot.set_ylim([0, 1.0])
acc_plot.set_xlim([batches[0], batches[-1]])
acc_plot.legend(loc=4)
plt.tight_layout()
plt.show()
Epoch  1/100: 100%|██████████| 416/416 [02:12<00:00,  3.20batches/s]
Epoch  2/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch  3/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch  4/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch  5/100: 100%|██████████| 416/416 [02:10<00:00,  3.21batches/s]
Epoch  6/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch  7/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch  8/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch  9/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 10/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 11/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 12/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 13/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 14/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 15/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 16/100: 100%|██████████| 416/416 [02:10<00:00,  3.21batches/s]
Epoch 17/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 18/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 19/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 20/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 21/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 22/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 23/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 24/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 25/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 26/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 27/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 28/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 29/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 30/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 31/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 32/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 33/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 34/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 35/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 36/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 37/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 38/100: 100%|██████████| 416/416 [02:10<00:00,  3.21batches/s]
Epoch 39/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 40/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 41/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 42/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 43/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 44/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 45/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 46/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 47/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 48/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 49/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 50/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 51/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 52/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 53/100: 100%|██████████| 416/416 [02:10<00:00,  3.21batches/s]
Epoch 54/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 55/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 56/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 57/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 58/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 59/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 60/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 61/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 62/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 63/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 64/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 65/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 66/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 67/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 68/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 69/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 70/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 71/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 72/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 73/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 74/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 75/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 76/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 77/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 78/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 79/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 80/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 81/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 82/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 83/100: 100%|██████████| 416/416 [02:10<00:00,  3.18batches/s]
Epoch 84/100: 100%|██████████| 416/416 [02:10<00:00,  3.20batches/s]
Epoch 85/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 86/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 87/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 88/100: 100%|██████████| 416/416 [02:10<00:00,  3.19batches/s]
Epoch 89/100: 100%|██████████| 416/416 [02:11<00:00,  3.19batches/s]
Epoch 90/100: 100%|██████████| 416/416 [02:11<00:00,  3.18batches/s]
Epoch 91/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 92/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 93/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 94/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 95/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 96/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 97/100: 100%|██████████| 416/416 [02:11<00:00,  3.16batches/s]
Epoch 98/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 99/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Epoch 100/100: 100%|██████████| 416/416 [02:11<00:00,  3.17batches/s]
Final validation accuracy:  0.993846223905
Final test accuracy:  0.911031732957

Question 1

Describe the techniques used to preprocess the data.

Answer:

In [22]:
"""
I noted that some classes were very underrepresented in the training data, some by a 1:9 ratio compared to some others
So for these classes, I generated additional data by rotating the pictures by incremental small angles
until I had a roughly similar amount of inputs for each class.

I then normalized the values between 0.1 and 0.9

Finally, as the input was sorted by class, I randomized it to avoid overfitting.
"""

test_batch_size = 250
y_pred_cls = tf.argmax(prediction, dimension=1)
test_cls = np.argmax(oh_test_labels, axis=1)
from pylab import rcParams
from sklearn.metrics import confusion_matrix

img_shape = (32, 32, 3)
def plot_images(images, cls_true, cls_pred=None):
    assert len(images) == len(cls_true) == 9
    
    # Create figure with 3x3 sub-plots.
    fig, axes = plt.subplots(3, 3)
    fig.subplots_adjust(hspace=0.3, wspace=0.3)

    for i, ax in enumerate(axes.flat):
        # Plot image.
        ax.imshow(images[i].reshape(img_shape), cmap='binary')

        # Show true and predicted classes.
        if cls_pred is None:
            xlabel = "True: {0}".format(np.argmax(cls_true[i]))
        else:
            xlabel = "True: {0}, Pred: {1}".format(np.argmax(cls_true[i]), np.argmax(cls_pred[i]))

        # Show the classes as the label on the x-axis.
        ax.set_xlabel(xlabel)
        
        # Remove ticks from the plot.
        ax.set_xticks([])
        ax.set_yticks([])
    
    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show()
    
def plot_confusion_matrix(cls_pred):
    # This is called from print_test_accuracy() below.

    # cls_pred is an array of the predicted class-number for
    # all images in the test-set.

    
    # Get the confusion matrix using sklearn.
    cm = confusion_matrix(y_true=test_cls,
                          y_pred=cls_pred)

    plt.figure(figsize=(40,40))
    rcParams['figure.figsize'] = 13, 13
    # Plot the confusion matrix as an image.
    plt.matshow(cm)

    # Make various adjustments to the plot.
    plt.colorbar()
    tick_marks = np.arange(n_classes)
    plt.xticks(tick_marks, range(n_classes))
    plt.yticks(tick_marks, range(n_classes))
    plt.xlabel('Predicted')
    plt.ylabel('True')
    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.    
    plt.show()
    

def plot_example_errors(cls_pred, correct):
    # This function is called from print_test_accuracy() below.

    # cls_pred is an array of the predicted class-number for
    # all images in the test-set.

    # correct is a boolean array whether the predicted class
    # is equal to the true class for each image in the test-set.

    # Negate the boolean array.
    incorrect = (correct == False)
    
    # Get the images from the test-set that have been
    # incorrectly classified.
    images = test_features[incorrect]
    
    # Get the predicted classes for those images.
    cls_pred = cls_pred[incorrect]

    # Get the true classes for those images.
    cls_true = test_cls[incorrect]
    
    # Plot the first 9 images.
    plot_images(images=images[0:9],
                cls_true=cls_true[0:9],
                cls_pred=cls_pred[0:9])
    
def print_test_accuracy(show_example_errors=False,
                        show_confusion_matrix=False):

    # Number of images in the test-set.
    num_test = len(test_features)

    # Allocate an array for the predicted classes which
    # will be calculated in batches and filled into this array.
    cls_pred = np.zeros(shape=num_test, dtype=np.int)

    # Now calculate the predicted classes for the batches.
    # We will just iterate through all the batches.
    # There might be a more clever and Pythonic way of doing this.

    # The starting index for the next batch is denoted i.
    i = 0

    while i < num_test:
        # The ending index for the next batch is denoted j.
        j = min(i + test_batch_size, num_test)

        batch_features = test_features[i:j]
        batch_labels = oh_test_labels[i:j]
        
        # Create a feed-dict with these images and labels.
        feed_dict={input_ph: batch_features, labels_ph: batch_labels}

        # Calculate the predicted class using TensorFlow.
        cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)
        # Set the start-index for the next batch to the
        # end-index of the current batch.
        i = j

    # Create a boolean array whether each image is correctly classified.
    correct = (test_cls == cls_pred)

    # Calculate the number of correctly classified images.
    # When summing a boolean array, False means 0 and True means 1.
    correct_sum = correct.sum()

    # Classification accuracy is the number of correctly classified
    # images divided by the total number of images in the test-set.
    acc = float(correct_sum) / num_test

    # Print the accuracy.
    msg = "Accuracy on Test-Set: {0:.1%} ({1} / {2})"
    print(msg.format(acc, correct_sum, num_test))

    # Plot some examples of mis-classifications, if desired.
    if show_example_errors:
        print("Example errors:")
        plot_example_errors(cls_pred=cls_pred, correct=correct)

    # Plot the confusion matrix, if desired.
    if show_confusion_matrix:
        print("Confusion Matrix:")
        plot_confusion_matrix(cls_pred=cls_pred)

print_test_accuracy(show_example_errors=False, show_confusion_matrix=True)
Accuracy on Test-Set: 91.1% (11505 / 12630)
Confusion Matrix:
<matplotlib.figure.Figure at 0x7f39105167f0>

Question 2

Describe how you set up the training, validation and testing data for your model. If you generated additional data, why?

Answer:

In [ ]:
"""
I took 20% of the training data as validation data, which seemed enough to not overfit the data.
I didn't use the testing data until I got satisfying results with the network.
"""

Question 3

What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.

Answer:

In [ ]:
"""
First layer is a CNN with a patch size of 3*3, a stride of 1, SAME padding and a depth of 64
Second and third layers are fully connected layers with a width of 512
The final layer is a fully connected layer with a width of 43 (the amount of classes)
"""

Question 4

How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)

Answer:

In [ ]:
"""
I used the Adam optimizer with its default parameters as it is currently regarded as the most efficient.
I used a batch size of 250 and 30 training epochs.
"""

Question 5

What approach did you take in coming up with a solution to this problem?

Answer:

In [ ]:
"""
I tried adding more convolution networks but they didn't improve the results and increased the computation time by a lot.
It didn't feel that necessary to add them as there is a low statistical invariance between the pictures we work on.
Most of them are already centered and cropped around the sign.

I used a medium sized network as the signs are overall pretty simple in shape and color.
I used wide fully connected layers as there are some variations in the sign's shapes, colors and overall appearance.

I didn't use more than 30 epochs as the accuracy wasn't improving after that.

I also wanted to keep the network light so training it wouldn't take too much time on AWS and the results are satisfying as is.
"""

Step 3: Test a Model on New Images

Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [25]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg

imgs = ['20.png', '80.png', 'exclamation.png', 'hochwasser.png', 'priority.png']

new_input = []

for imgname in imgs:
    image = mpimg.imread('images/' + imgname)
    new_input.append(image)
    plt.imshow(image)
    plt.show()

Question 6

Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It would be helpful to plot the images in the notebook.

Answer:

In [38]:
### Run the predictions here.
### Feel free to use as many code cells as needed.

new_predictions = session.run(prediction, feed_dict={input_ph: new_input})

Question 7

Is your model able to perform equally well on captured pictures or a live camera stream when compared to testing on the dataset?

Answer:

In [39]:
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
print(new_predictions)
[[  2.51535880e-06   6.13179212e-13   2.35583908e-08   9.99986529e-01
    1.79575965e-30   9.60767125e-07   1.76238631e-35   2.69539583e-29
    1.43326438e-19   6.00464365e-20   2.58030658e-30   4.20702743e-33
    0.00000000e+00   9.96053041e-06   1.25320303e-14   1.00141426e-30
    3.14934289e-26   5.42002901e-12   1.13559734e-34   0.00000000e+00
    3.57751741e-12   0.00000000e+00   4.95198232e-35   8.70952638e-33
    0.00000000e+00   1.78704165e-13   0.00000000e+00   0.00000000e+00
    3.42013864e-22   8.30619494e-24   0.00000000e+00   2.21580986e-30
    2.22022567e-23   0.00000000e+00   0.00000000e+00   2.39133828e-33
    2.27727674e-31   0.00000000e+00   2.81211697e-22   0.00000000e+00
    0.00000000e+00   1.04412353e-35   1.08266547e-33]
 [  0.00000000e+00   4.55995603e-03   1.19986412e-08   1.87258419e-14
    0.00000000e+00   9.95440006e-01   1.51333885e-36   0.00000000e+00
    0.00000000e+00   0.00000000e+00   1.66548798e-26   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   2.99156362e-26   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   3.22352457e-36
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   4.05786776e-27   1.60297416e-31   6.76811822e-36
    0.00000000e+00   3.68482129e-27   0.00000000e+00   0.00000000e+00
    2.80600996e-30   0.00000000e+00   0.00000000e+00   6.98117887e-13
    3.88300423e-35   0.00000000e+00   5.29719770e-22   0.00000000e+00
    0.00000000e+00   2.63366776e-32   9.98393834e-01   0.00000000e+00
    1.19629308e-31   0.00000000e+00   1.57698780e-35   0.00000000e+00
    9.31296213e-27   1.60617393e-03   2.61515214e-28   5.82654805e-19
    7.35338626e-31   5.18789586e-19   3.00157414e-26   9.47776823e-16
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   8.80440652e-01   1.47310394e-25   1.75838967e-36
    1.08719814e-24   0.00000000e+00   0.00000000e+00   0.00000000e+00
    1.40014213e-20   0.00000000e+00   0.00000000e+00   1.76057956e-34
    5.39842279e-35   0.00000000e+00   0.00000000e+00   1.68365787e-05
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   6.11776102e-32
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   1.19542591e-01   8.95230108e-32]
 [  6.71977769e-38   9.99999404e-01   1.82343176e-27   4.36727260e-13
    0.00000000e+00   2.05941722e-11   3.40928700e-33   0.00000000e+00
    2.26185410e-14   2.00576945e-25   6.04400110e-33   7.01803785e-34
    7.79207102e-13   1.15005712e-23   0.00000000e+00   0.00000000e+00
    0.00000000e+00   7.22239422e-32   1.97672350e-32   0.00000000e+00
    8.08867421e-15   0.00000000e+00   0.00000000e+00   3.03645342e-23
    0.00000000e+00   4.15063255e-08   0.00000000e+00   0.00000000e+00
    3.99866089e-29   5.45426246e-07   0.00000000e+00   3.02866951e-22
    3.45676764e-28   0.00000000e+00   0.00000000e+00   1.36918443e-09
    1.38165035e-32   0.00000000e+00   3.33631144e-11   0.00000000e+00
    7.64897590e-38   1.59949930e-17   1.57156730e-19]]

Question 8

Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)

Answer:

In [73]:
print(session.run(tf.nn.top_k(prediction, 2), feed_dict={input_ph: new_input}))

"""
The model is pretty certain of all of its results except for one where it's only at 88% certainty.
When the model is wrong, the correct answer does not appear in the top 2. Prediction certainty after class 2 are meaningless so we don't analyze them.
"""
TopKV2(values=array([[  9.99986529e-01,   9.96053041e-06],
       [  9.95440006e-01,   4.55995603e-03],
       [  9.98393834e-01,   1.60617393e-03],
       [  8.80440652e-01,   1.19542591e-01],
       [  9.99999404e-01,   5.45426246e-07]], dtype=float32), indices=array([[ 3, 13],
       [ 5,  1],
       [18, 25],
       [ 9, 41],
       [ 1, 29]], dtype=int32))
Out[73]:
"\nThe model is pretty certain of all of its results except for one where it's only at 88% certainty.\nWhen the model is wrong, the correct answer does not appear in the top 2. Prediction certainty after class 2 are meaningless so we don't analyze them.\n"

Question 9

If necessary, provide documentation for how an interface was built for your model to load and classify newly-acquired images.

Answer:

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In [ ]: